//
//  ComposeViewController.swift
//  JKDWeiBoExercise
//
//  Created by 简康达 on 16/6/12.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
class ComposeViewController: UIViewController {
//    MARK:- 约束属性
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
//    MARK:- 控件属性
    @IBOutlet weak var composeTextView: ComposeTextView!
    @IBOutlet weak var toolBar: UIToolbar!
//    MARK:- 懒加载属性
    private var picPickerVC : PicPickerViewController = PicPickerViewController(collectionViewLayout: PicPickerCollectionViewLayout())
    private lazy var titleView : ComposeTitleView = ComposeTitleView()
    private lazy var emoticonVC : EmoticonViewController = EmoticonViewController { [weak self](emoticon) in
        self?.composeTextView.insertEmoticon(emoticon)
        self?.textViewDidChange((self?.composeTextView)!)
    }
    override func viewDidLoad() {
        setupNavigationItem()
        setupPicPickerView()
//    MARK:- 监听键盘的弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        composeTextView.becomeFirstResponder()
    }
//    MARK;- 控制器销毁时，移除监听
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
//MARK:- UI相关设置
extension ComposeViewController {
    private func setupNavigationItem(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(ComposeViewController.cancelItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: #selector(ComposeViewController.postItemClick))
        navigationItem.rightBarButtonItem?.enabled = false
        titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 36)
        navigationItem.titleView = titleView
    }
    private func setupPicPickerView(){
        self.addChildViewController(picPickerVC)
//        添加到工具栏之下
        self.view.insertSubview(picPickerVC.view, belowSubview:toolBar)
        picPickerVC.view.snp_makeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(0)
        }
    }
}
//MARK:- 监听事件
extension ComposeViewController{
    /// 左侧取消按钮的监听
   @objc private func cancelItemClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// 右侧发生按钮的监听
   @objc private func postItemClick(){
    SVProgressHUD.show()
    let image = picPickerVC.images.first
    let text = composeTextView.getEmoticonString()
    NetworkTools.shareIntance.composeStatus(text: text, image: image) { (isSucess) in
        if isSucess {
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
        }else{
            SVProgressHUD.showErrorWithStatus("发布微博失败")
        }
    }
    dismissViewControllerAnimated(true, completion: nil)
    }
    /// 发布界面输入键盘的监听
    @objc private func keyboardWillChangeFrame(note:NSNotification){
        let endFrameValue = note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let endFrame = endFrameValue.CGRectValue()
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        UIView.animateWithDuration(duration) {
//            中段之前的动画，执行下一次动画
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: 7)!)
            self.toolBarBottomCons.constant = UIScreen.mainScreen().bounds.height - endFrame.origin.y
        }
    }
    ///监听选择图片按钮的点击
    @IBAction func picPickerBtnClick() {
//        退出键盘
        composeTextView.resignFirstResponder()
        picPickerVC.view.snp_remakeConstraints { (make) in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(self.view.snp_height).multipliedBy(0.65)
        }
        UIView.animateWithDuration(0.5) {
            self.view.layoutIfNeeded()
        }
    }
    ///监听表情图片按钮的点击
    @IBAction func emoticonBtnClick() {
//        退出键盘
        composeTextView.resignFirstResponder()
//        切换键盘
        composeTextView.inputView = composeTextView.inputView == nil ? emoticonVC.view : nil
//        弹出键盘
        composeTextView.becomeFirstResponder()
    }

    }
//MARK:- 遵守协议，实现代理方法
extension ComposeViewController : UITextViewDelegate{
    ///文字发生改变时会调用
    func textViewDidChange(textView: UITextView) {
        composeTextView.placeHolderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    ///拖拽composeTextView时会调用
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }
}